package com.boyi.center.exception;

import com.boyi.shared.common.Message;
import com.boyi.shared.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tingwen
 * @date 2018年08月03日  下午 05:31
 */
@RestControllerAdvice("com.boyi")
public class MyExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e) {
        Map<String, String> data = new HashMap<>(16);
        for (ObjectError error : e.getAllErrors()) {
            data.put(((FieldError) error).getField(), error.getDefaultMessage());
        }
        if (logger.isDebugEnabled()) {
            logger.debug(Message.CHECK_ERROR.msg, data,e);
        }
        Result r = new Result();
        r.setMessage(Message.CHECK_ERROR);
        r.setData(data);
        return r;
    }

    @ExceptionHandler({Exception.class})
    public Result handleException(Exception e) {
        logger.error(Message.SERVER_EXCEPTION.msg, e);
        Result r = new Result();
        r.setMessage(Message.SERVER_EXCEPTION);
        r.setData(e.getMessage());
        return r;
    }

}
